function p = correlpvalue(r, n, ot)
% correlpvalue  - pvalue of correlation coefficient
%
% FORMAT:       p = correlpvalue(r, n [, ot])
%
% Input fields:
%
%       r           correlation values (0 ... 1)
%       n           number of points in correlated series
%       ot          one-tailed, if given use one-tailed statistic
%
% Output fields:
%
%       p           alpha probability of false alarm for significance
%
% Note: by default, a two-tailed p-value is computed.
%
% See also correltstat.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isnumeric(r) || ...
   ~isnumeric(n) || ...
    isempty(r) || ...
    isempty(n) || ...
    any(isnan(r(:)) | isinf(r(:))) || ...
    any(isinf(n(:)) | isnan(n(:)) | n(:) < 2)
    error( ...
        'BVQXtools:BadArgument', ...
        'Missing or invalid argument given.' ...
    );
end
osize = size(r);
if numel(r) == 1 && ...
    numel(n) > 1
    osize = size(n);
end
if ~isa(r, 'double')
    r = double(r(:));
else
    r = r(:);
end
if ~isa(n, 'double')
    n = double(n(:));
else
    n = n(:);
end

% remove invalid entries
r(abs(r) > 1) = 0;

% compute p value from 2-tailed t-statistic
if nargin < 3
    p = 2 .* custom_tcdf(correltstat(-abs(r), n), n - 2);
else
    p = custom_tcdf(correltstat(-abs(r), n), n - 2);
end
p = reshape(p, osize);
